from django.db.models import Max
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.urls import reverse

from classroomBasicInfo.models import Classroombasicinfo, Facility, Building
import json


def index(request):
    b_list = Building.objects \
        .all() \
        .values("building_id", "building_name")  # 楼栋
    c_list = Classroombasicinfo.objects \
        .all() \
        .values("building_id", "classroom_name")  # 教室
    building_floor_room = {}  # 楼栋-楼层-教室
    for b in b_list:
        building_floor_room[b["building_id"]] = {
            "name": b["building_name"],
            "floor": {}
        }
        temp = [c for c in c_list if c["building_id"] == b["building_id"]]  # 楼栋筛选
        temp.sort(key=lambda x: x["classroom_name"])  # 教室号排序
        for t in temp:
            f = t["classroom_name"] // 100  # 楼层
            r = t["classroom_name"] % 100  # 教室
            if f not in building_floor_room[b["building_id"]]["floor"].keys():
                building_floor_room[b["building_id"]]["floor"][f] = [r]
            else:
                building_floor_room[b["building_id"]]["floor"][f].append(r)

    return render(request, "admin_basicInfo.html", {"building_floor_room": json.dumps(building_floor_room)})


def search_classroom(request):
    # 检错
    try:
        b = int(request.POST["building"])
        f = int(request.POST["floor"])
        r = int(request.POST["room"])
    except:
        return JsonResponse({"flag": "输入出错"})
    # 查询
    try:
        classroom = Classroombasicinfo.objects \
            .values("building_id", "cid", "classroom_name", "capacity", "notice") \
            .get(building_id=b, classroom_name=f * 100 + r)
    except:
        return JsonResponse({"flag": "查询出错"})

    return JsonResponse({
        "flag": 0,
        "building_id": classroom["building_id"],
        "classroom_id": classroom["cid"],
        "classroom_name": classroom["classroom_name"],
        "capacity": classroom["capacity"],
        "notice": classroom["notice"]
    })


def search_facilities(request):
    # 检错
    try:
        b = int(request.POST["building_id"])
        c = int(request.POST["classroom_id"])
    except:
        return JsonResponse({
            "code": 0,
            "flag": "教室id错误"
        })
    # 查询所有
    if "f_name-in" not in request.POST:
        try:
            facilities = Facility.objects \
                .values("fid", "f_name", "category", "f_num") \
                .filter(building_id=b, cid=c)
        except:
            return JsonResponse({
                "code": 0,
                "flag": "查询设备出错"
            })
    # 设备名查询
    else:
        try:
            facilities = Facility.objects \
                .values("fid", "f_name", "category", "f_num") \
                .filter(building_id=b, cid=c, f_name__contains=request.POST["f_name-in"])
        except:
            return JsonResponse({
                "code": 0,
                "flag": "查询设备出错"
            })

    return JsonResponse({
        "code": 0,
        "flag": 0,
        "data": [{
            "id": f["fid"],
            "name": f["f_name"],
            "category": f["category"],
            "classroom": request.POST["classroom_name"],
            "number": f["f_num"]
        } for f in facilities]
    })


def update_classroom(request):
    # 检错
    try:
        b = int(request.POST["building_id"])
        cid = int(request.POST["classroom_id"])
        c = int(request.POST["capacity-in"])
    except:
        return JsonResponse({"flag": "输入错误"})
    if c < 0:
        return JsonResponse({"flag": "教室容量错误"})
    # 更新
    try:
        Classroombasicinfo.objects \
            .filter(building_id=b, cid=cid) \
            .update(capacity=c, notice=request.POST["notice-in"])
    except:
        return JsonResponse({"flag": "更新教室失败"})

    return JsonResponse({"flag": 0})


def update_facility(request):
    # 检错
    try:
        fid = int(request.POST["fid-in"])
    except:
        return JsonResponse({"flag": "设备id错误"})
    try:
        n = int(request.POST["f_num-in"])
    except:
        return JsonResponse({"flag": "设备数量错误"})
    if n < 0:
        return JsonResponse({"flag": "设备数量错误"})
    if "f_name-in" not in request.POST or "category-in" not in request.POST:
        return JsonResponse({"flag": "输入错误"})
    # 更新
    try:
        Facility.objects \
            .filter(fid=fid) \
            .update(f_name=request.POST["f_name-in"], category=request.POST["category-in"], f_num=n)
    except:
        return JsonResponse({"flag": "更新失败"})

    return JsonResponse({"flag": 0})


def delete_classroom(request):
    # 检错
    try:
        bid = int(request.POST["building_id"])
        cid = int(request.POST["classroom_id"])
    except:
        return JsonResponse({"flag": "楼栋或楼层id错误"})
    # 删除
    try:
        Classroombasicinfo.objects \
            .filter(building_id=bid, cid=cid) \
            .delete()
    except:
        return JsonResponse({"flag": "删除失败"})

    return JsonResponse({"flag": 0})


def delete_facility(request):
    # 检错
    try:
        fid = int(request.POST["fid-in"])
    except:
        return JsonResponse({"flag": "设备id错误"})
    # 删除
    try:
        Facility.objects \
            .filter(fid=fid) \
            .delete()
    except:
        return JsonResponse({"flag": "删除失败"})

    return JsonResponse({"flag": 0})


def add_classroom(request):
    # 检错
    try:
        bid = int(request.POST["building_id"])
        cname = int(request.POST["classroom_name"])
    except:
        return JsonResponse({"flag": "楼栋或教室id错误"})
    try:
        capacity = int(request.POST["capacity"])
    except:
        return JsonResponse({"flag": "教室容量错误"})
    if capacity < 0:
        return JsonResponse({"flag": "教室容量错误"})
    if "notice" not in request.POST or "attribute" not in request.POST:
        return JsonResponse({"flag": "输入错误"})
    # 查询id最值
    try:
        last = Classroombasicinfo.objects \
            .filter(building_id=bid) \
            .values("cid") \
            .aggregate(Max("cid"))
    except:
        return JsonResponse({"flag": "查询错误"})
    # 该楼层没有过记录
    if last["cid__max"] is None:
        cid = 1
    else:
        cid = last["cid__max"] + 1
    # 添加
    try:
        Classroombasicinfo.objects \
            .create(building_id=bid, cid=cid, classroom_name=cname, capacity=capacity,
                    notice=request.POST["notice"], attribute=request.POST["attribute"])
    except:
        return JsonResponse({"flag": "添加失败"})

    return JsonResponse({"flag": 0})


def add_facility(request):
    # 检错
    try:
        bid = int(request.POST["building_id"])
        cid = int(request.POST["classroom_id"])
    except:
        return JsonResponse({"flag": "教室或楼栋id错误"})
    try:
        n = int(request.POST["f_num-in"])
    except:
        return JsonResponse({"flag": "设备数量错误"})
    if n < 0:
        return JsonResponse({"flag": "设备数量错误"})
    if "f_name-in" not in request.POST or "category-in" not in request.POST:
        return JsonResponse({"flag": "输入错误"})
    # 添加
    try:
        Facility.objects \
            .create(building_id=bid, cid=cid, f_name=request.POST["f_name-in"], category=request.POST["category-in"],
                    f_num=n)
    except:
        return JsonResponse({"flag": "添加失败"})

    return JsonResponse({"flag": 0})